/**
 *  Copyright ${date} Matthew Cline
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package factbook;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;

/**
 * An implementation of FactbookSource that uses the zip archive of the Factbook.
 * This archive is available for download from the CIA website.
 * 
 * @author Matthew Cline
 *
 */
public class FactbookZIP implements FactbookSource {

	private boolean debug = false;
	
	private ZipFile factbookFile;
	
	public FactbookZIP(File file) throws ZipException, IOException {
		factbookFile = new ZipFile(file);
	}
	
	public String get(String fips, String field) throws MalformedURLException, IOException {
		String entryPath = "factbook/geos/" + fips + ".html";
		
		if(debug) {
			for (Enumeration e = factbookFile.entries(); e.hasMoreElements();) {
				ZipEntry entry = (ZipEntry)e.nextElement();
				System.err.println(entry.getName());
			}
		}
		
		BufferedInputStream in = new BufferedInputStream(factbookFile.getInputStream(factbookFile.getEntry(entryPath)));
		FactbookWebParser parser = new FactbookWebParser(in);
		String results = parser.get(fips, field);
		return results;
	}

}
